<template>
    <div>
        <a-card class="box-card" :style="{ marginTop: '15px' }" :cardOpen="true">
            <div slot="header">
                <span>处置流程</span>
            </div>
            <el-form ref="elForm" size="medium" label-width="100px">
                <el-row class="role-groups">
                    <div class="role-group-side">
                        <el-tree :data="plan.nodeList" ref="flowNodeList" node-key="nodeId" default-expand-all check-on-click-node highlight-current @node-click="onFlowNodeClick">
                            <span class="flow-node" slot-scope="{ node, data }">
                                <span class="flow-label">{{ data.nodeName }}</span>
                            </span>
                        </el-tree>
                    </div>
                    <div class="role-list">
                        <el-form-item label="流程控制" prop="event_name" v-if="canStartFlow && handleing">
                            <el-button type="success" size="mini" @click="handleStartFlow">开启流程</el-button>
                        </el-form-item>
                        <el-form-item label="处置任务" prop="event_name">
                            <el-row v-if="handleing">
                                <el-button type="primary" size="mini" @click="handleDrillTaskAdd">添加处置任务</el-button>
                            </el-row>
                            <handle-task-table ref="handleTaskTable" :tasks="nodeTasks" :handleId="handleId" @refreshCurrentTasks="queryCurrentNodeTasks" :handleing="handleing" @handleTaskEdit="handleTaskEdit" />
                        </el-form-item>
                    </div>
                </el-row>
            </el-form>
        </a-card>
        <el-row class="drill-btns" v-if="handleing">
            <el-button type="success" size="medium" @click="handleEndHandle">处置结束</el-button>
        </el-row>
        <handle-task-edit ref="handleTaskEdit" :taskType="handleInfo.type == 2 ? 'handle' : 'drill'" @handleOk="onDrillTaskSave" />
    </div>
</template>

<script>
import * as HandleApi from "@/api/response/handle.js";
import ACard from "@/views/components/a-card/card.vue";
import HandleTaskEdit from "./taskEdit.vue";
import HandleTaskTable from "../module/HandleTaskTable.vue";
import { selectDeptTaskByNodeId, addDeptTask, editDeptTask } from "@/api/response/task";

export default {
    name: "HandleDetailCard",
    components: { ACard, HandleTaskEdit, HandleTaskTable },
    dicts: ["sys_dept_type_dict"],
    props: {
        handleId: {
            type: Number,
            default: 0,
        },
        plan: {
            type: Object,
            default: () => {
                return {};
            },
        },
        handleing: {
            type: Boolean,
            default: true,
        },
    },
    data() {
        return {
            handleInfo: {},
            levels: [],
            responseLevelOption: [
                {
                    label: "Ⅰ级响应",
                    value: 1,
                },
                {
                    label: "Ⅱ级响应",
                    value: 2,
                },
                {
                    label: "Ⅲ级响应",
                    value: 3,
                },
                {
                    label: "Ⅳ级响应",
                    value: 4,
                },
            ],
            activeResponse: "1",
            currentLevel: null,
            currentFlow: null,
            drillPlanId: 0,
            nodeTasks: [],
            nodes: [],
            currentNodeId: "",
            timer: null,
        };
    },
    computed: {
        canStartFlow() {
            if (this.nodes.length == 0) return false;
            // 在nodes中按sort排序后找到第一个status == 0的
            this.nodes.sort((a, b) => {
                return a.sort - b.sort;
            });
            var firstNode;
            for (let i = 0; i < this.nodes.length; i++) {
                if (this.nodes[i].status == 0) {
                    firstNode = this.nodes[i];
                    break;
                }
            }
            if (!firstNode) {
                return false;
            }
            return firstNode.nodeId == this.currentNodeId;
        },
    },
    mounted() {
        // 预案数据更新后默认初始化第一个处置流程
        this.$refs.flowNodeList.setCurrentKey(this.plan.nodeList[0].nodeId);
        this.onFlowNodeClick(this.plan.nodeList[0]);
        this.getNodeProgress();
        this.$bus.$on("handle-detail-destroy", () => {
            if (this.timer) {
                clearInterval(this.timer);
            }
        });
    },
    methods: {
        getNodeProgress() {
            HandleApi.getHandleProgress(this.handleId).then(res => {
                this.nodes = res.data;
            });
        },
        getDrillGroupRoles() {
            DrillApi.getDrillGroupRole(this.handleId).then(res => {
                this.drillGroups = res.data;
            });
        },
        onFlowNodeClick(val) {
            this.currentNodeId = val.nodeId;
            // 根据节点ID获取任务列表
            this.queryCurrentNodeTasks();
        },
        queryCurrentNodeTasks() {
            selectDeptTaskByNodeId({
                handleId: this.handleId,
                nodeId: this.currentNodeId,
            }).then(res => {
                this.nodeTasks = res.data;
                if (this.timer == null) {
                    this.timer = setInterval(() => {
                        this.queryCurrentNodeTasks();
                    }, 5000);
                }
            });
        },
        handleDrillTaskAdd() {
            this.$refs.handleTaskEdit.add();
        },
        handleTaskEdit(data) {
            console.log(data);
            this.$refs.handleTaskEdit.edit(data);
        },
        onDrillTaskSave(data) {
            if (data.id) {
                // 修改
                editDeptTask({
                    id: data.id,
                    receiveUser: data.userId,
                    receiveUserName: data.userName,
                    taskDept: data.deptId,
                    taskDeptName: data.deptName,
                    taskContent: data.taskContent,
                    helpContent: data.helpContent,
                    ddl: data.ddl,
                    attachIds: data.attachIds,
                }).then(res => {
                    this.$refs.handleTaskEdit.close();
                    this.$modal.msgSuccess("处置任务编辑成功");
                    this.queryCurrentNodeTasks();
                });
            } else {
                addDeptTask({
                    handleId: this.handleId,
                    nodeId: this.currentNodeId,
                    receiveUser: data.userId,
                    receiveUserName: data.userName,
                    taskDept: data.deptId,
                    taskDeptName: data.deptName,
                    taskContent: data.taskContent,
                    helpContent: data.helpContent,
                    ddl: data.ddl,
                    attachIds: data.attachIds,
                }).then(res => {
                    this.$refs.handleTaskEdit.close();
                    this.$modal.msgSuccess("处置任务编辑成功");
                    this.queryCurrentNodeTasks();
                });
            }
        },
        handleEndHandle() {
            this.$modal.confirm("结束处置请确保所有处置任务均已完成，是否确定结束？").then(() => {
                HandleApi.setHandleEnd({ handleId: this.handleId })
                    .then(res => {
                        //成功结束，关闭当前页面，刷新处置列表页
                        this.$tab.closePage().then(res => {
                            this.$tab.refreshPage({
                                path: "/response/handleList",
                                name: "HandleList",
                            });
                        });
                    })
                    .catch(e => {
                        // 提示错误
                        console.log(e);
                        this.$modal.msgError(e.message);
                    });
            });
        },
        handleSceneChange(val) {
            this.currentLevel = this.levels[this.activeResponse - 1];
            this.$nextTick(() => {
                this.$refs.flowNodeList.setCurrentKey(this.currentLevel.plaHandleVos[0].handleId);
                let node = this.$refs.flowNodeList.getCurrentNode();
                this.onFlowNodeClick(this.currentLevel.plaHandleVos[0], node);
            });
        },
        setCurrentTasks(data) {
            this.currentFlow.hdTasks = data;
        },

        handleStartFlow() {
            let allTaskHasReceiverUser = this.$refs.handleTaskTable.isAllTaskHasReceiverUser();
            if (!allTaskHasReceiverUser) {
                this.$modal.msgError("请为当前流程每个任务选择执行人员");
                return;
            }
            HandleApi.openHandle({
                handleId: this.handleId,
                nodeId: this.currentNodeId,
            })
                .then(res => {
                    this.getNodeProgress();
                    this.queryCurrentNodeTasks();
                })
                .catch(e => {
                    this.$modal.msgError(e.message);
                });
        },
    },
    watch: {
        plan: () => {},
    },
};
</script>

<style lang="scss" scoped>
.role-groups {
    display: flex;

    .role-group-side {
        min-width: 200px;
    }

    .role-list {
        flex: 1;
        margin-left: 15px;
        box-sizing: content-box;
        overflow: hidden;
    }
}

::v-deep {
    .el-tree-node__content {
        display: flex;

        .flow-node {
            flex: 1;
            display: flex;

            .flow-label {
                flex: 1;
                line-height: 28px;
            }

            .flow-btns {
                margin-right: 10px;
            }
        }
    }

    .el-button.tab-edit-btn {
        color: #13ce66;
        margin-left: 10px;
        font-size: 12px;
    }
}

.feed-container {
    background: #0b133c;
    color: white;
    border-radius: 10px;
    padding: 15px;

    .feed-list {
        overflow-y: scroll;
        max-height: 300px;

        // 设置滚动条宽度
        &::-webkit-scrollbar {
            width: 8px !important;
            height: 8px !important;
            background: rgba(10, 122, 227, 0.01);
        }

        //滚动条的哈滑块
        &::-webkit-scrollbar-thumb {
            background: #2e6190;
            border-radius: 3px;
        }

        .feed-item {
            font-size: 12px;
            line-height: 25px;
        }
    }
}

ul,
li {
    padding: 0;
    margin: 0;
}

li {
    list-style: none;
}

.drill-btns {
    text-align: center;
    margin-top: 20px;
}
</style>
